var LOCALE = document.body.classList.contains('lang-zh') ? 'zh' : 'en'
var IS_DEV = location.hostname !== 'www.starbucks.com.cn';
var IS_STAGING = location.hostname === 'web-staging-sbux.starbucks.com.cn';
var IS_PRODUCTION = location.hostname === 'www.starbucks.com.cn';
var API_HOST = '';
var CDN_PREFIX = '';
if(IS_PRODUCTION) {
  API_HOST = 'https://bff.starbucks.com.cn';
  CDN_PREFIX = 'https://www-static.chinacdn.starbucks.com.cn/prod';
}
else if(IS_STAGING) {
  API_HOST = 'https://bff.stg.starbucks.com.cn';
  CDN_PREFIX = 'https://www-static.chinacdn.stg.starbucks.com.cn';
}
else {
  API_HOST = '/apis';
  CDN_PREFIX = 'https://www-static.chinacdn.stg.starbucks.com.cn';
}

function getBannerConfig(bannerType, cacheKey, defaultBannerConfig, handleResFunc) {  
  var apiURL = '/app-provision-api/default/banner?bannerType=' + bannerType;
  var useStorageMsg = 'use local storage';
  var useApiMsg = 'use api result';
  var useDefaultMsg = 'use banner config in default';

  var cache = window.localStorage.getItem(cacheKey);
  if(cache){
    console.log(cacheKey, useStorageMsg);
    handleResFunc(JSON.parse(cache));
  }
  $.ajax({
    url: API_HOST + apiURL,
    type: "GET",
    headers: {
      'Accept': 'application/json'
    }
  }).then((result) => {
    console.log(`璇锋眰${bannerType}鏁版嵁鎴愬姛锛乣);

    if(result && result.length > 0) {
      resetCache(cache, cacheKey, result, useApiMsg, handleResFunc);
    } else {
      resetCache(cache, cacheKey, defaultBannerConfig, useDefaultMsg, handleResFunc);
    }
    if(bannerType === "homepage-banner") {
      addCarouselAnimation()
    }
  }, () => {
    console.error(`璇锋眰${bannerType}鏁版嵁澶辫触锛乣);
    resetCache(cache, cacheKey, defaultBannerConfig, useDefaultMsg, handleResFunc);
    if(bannerType === "homepage-banner") {
      addCarouselAnimation()
    }
  })
}

function resetCache(cache, cacheKey, result_json, message, handleResFunc) {
  var result_str = JSON.stringify(result_json);
  if(cache !== result_str) {
    console.log(cacheKey, message);
    window.localStorage.setItem(cacheKey, result_str);
    handleResFunc(result_json);
  }
}